package com.brewster.config.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.brewster.config.model.Account;
import com.brewster.config.model.Menu;
import com.brewster.config.model.Role;
import com.jfinal.kit.LogKit;

/**
 * Created by jie on 2017/4/3. 自定义shiro Realm
 */
public class ShiroDbRealm extends AuthorizingRealm {
	static final Account accountDao = new Account();
	static final Role roleDao = new Role();
	static final Menu menuDao = new Menu();

	/**
	 * 认证回调函数,登录时调用.
	 * 
	 * @param authcToken 登录信息集合
	 * @return AuthenticationInfo
	 * @throws AuthenticationException 认证异常
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Account account = accountDao.login(token.getUsername(), new String(token.getPassword()), false,
				token.getHost());
		// 账号不存在
		if (account == null)
			throw new UnknownAccountException();// 没找到帐号
		if ("1".equals(account.get("del_flag"))) {
			throw new LockedAccountException();
		}

		List<Menu> buttonsPermisson = menuDao.getButtonsByRoleids(account.getStr("role_id"));
		List<String> buttonList = new ArrayList<String>();
		for (int i = 0; i < buttonsPermisson.size(); i++) {
			buttonList.add(buttonsPermisson.get(i).getStr("permission"));
		}
		account.setPermission(buttonList);
		return new SimpleAuthenticationInfo(account, account.getPassword(), ByteSource.Util.bytes(account.getSalt()),
				getName());

//		return new SimpleAuthenticationInfo(sysUser.getUsername(),sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getSalt()), getName());
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 * 
	 * @param principals 授权信息
	 * @return AuthorizationInfo
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		LogKit.info("判断用户权限");
		Account account = (Account) principals.fromRealm(getName()).iterator().next();
		SimpleAuthorizationInfo authinfo = new SimpleAuthorizationInfo();
		authinfo.addRole("role_" + account.getStr("role_id"));
		List<Menu> menuList = menuDao.getButtonsByRoleids(account.getStr("role_id"));
		List<String> lists = new ArrayList<String>();
		for (Menu menu : menuList) {
			lists.add(menu.getStr("permission"));
		}
		authinfo.addStringPermissions(lists);
		return authinfo;
	}

	/**
	 * 更新用户授权信息缓存.
	 * 
	 * @param principal 用户标志
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	// 清除缓存
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

}